package service

import (
	"api-wareway/basic/config"
	__ "api-wareway/basic/proto"
	"api-wareway/handler/request"
	"github.com/gin-gonic/gin"
	"net/http"
)

func SendSms(c *gin.Context) {
	var form request.SendSmsForm

	err := c.ShouldBind(&form)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "验证失败",
		})
		return
	}

	_, err = config.UserClient.SendSms(c, &__.SendSmsReq{
		Mobile: form.Mobile,
		Source: form.Source,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "发送失败",
			"data": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "短信发送成功",
	})

}

func RegisterUser(c *gin.Context) {
	var form request.RegisterForm

	err := c.ShouldBind(&form)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "验证失败",
		})
		return
	}
	user, err := config.UserClient.CreateUser(c, &__.CreateUserReq{
		Mobile:   form.Mobile,
		Password: form.Password,
		Sms:      form.Sms,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "注册失败",
			"data": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "注册成功",
		"data": user,
	})

}

func LoginUser(c *gin.Context) {
	var form request.LoginUserForm

	err := c.ShouldBind(&form)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "验证失败",
		})
		return
	}

	user, err := config.UserClient.LoginUser(c, &__.LoginUserReq{
		Mobile:   form.Mobile,
		Password: form.Password,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "登录失败",
			"data": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
}
